/**
 * FileName: OAuthInfo Author:   zeroleavebaoyang Date:     2018/9/4 11:27 Description:
 */
package com.shiro.sso.demo.oauth2;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shiro.sso.demo.model.User;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import lombok.Data;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

@Data
public class OAuthInfo {

    private String clientId;
    private String apiKey;
    private String secretKey;
    private String scope;
    private String redirectUri;
    private String apiBaseUrl;
    private String authUrl;
    private String tokenUrl;
    private String userInfoApi;
    private String portraitUrlTemplate;


    public String getUserInfoAuthUrl() {
        Map<String, String> params = new HashMap<String, String>();
        params.put("clientId", clientId);
        params.put("apiKey", apiKey);
        params.put("secretKey", secretKey);
        params.put("scope", scope);
        params.put("redirectUri", redirectUri);
        return templateHandle(this.authUrl, params);
    }

    public String getUserInfoTokenUrl(String code) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("code", code);
        params.put("clientId", clientId);
        params.put("apiKey", apiKey);
        params.put("secretKey", secretKey);
        params.put("scope", scope);
        params.put("redirectUri", redirectUri);
        return templateHandle(this.tokenUrl, params);
    }

    public String getUserInfoApiUrl(String accessToken) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("clientId", clientId);
        params.put("apiKey", apiKey);
        params.put("secretKey", secretKey);
        params.put("scope", scope);
        params.put("apiBaseUrl", apiBaseUrl);
        params.put("accessToken", accessToken);
        return templateHandle(this.userInfoApi, params);
    }

    private String templateHandle(String template, Map<String, String> params) {
        Pattern regex = Pattern.compile("\\$\\{(.+?)\\}");
        Matcher matcher = regex.matcher(template);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            String key = matcher.group(1);
            String replaceVal = params.get(key);
            if (StringUtils.isBlank(replaceVal)) {
                continue;
            } else {
                matcher.appendReplacement(sb, replaceVal);
            }
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE);
    }

}
